from pyecharts import options as opts
from pyecharts.charts import Bar

import pymongo
from bson.json_util import dumps
import json
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["spider-db"]
collection = db["wzj_product"]
result = collection.find({})  # bjson格式的数据
json_str = dumps(result)  # 将数据库查询结果转为json字符串
json_obj = json.loads(json_str)  # 将json字符串转为python的数据对象
print(json_obj)
name_list = []  # 所有商品名称
min_list = []  # 所有商品最小价格
max_list = []  # 所有商品最高价格
color_list = []
color_arr = ['#2233dd', 'dd4455']
for each in json_obj:
    name_list.append(each["name"])
    min_list.append(each["min_price"])
    max_list.append(each["max_price"])
    idx = json_obj.index(each)
    color_list.append(idx/2)
    # 通过中断数据的提取，避免图表数据太过拥挤
    # if json_obj.index(each) >= 10:
    #     break
tree = (
    Bar()
    .add_xaxis(
        name_list
    )
    .add_yaxis("最低价", min_list)
    .add_yaxis("最高价", max_list, color=color_list)
)
tree.set_global_opts(
    datazoom_opts=opts.DataZoomOpts(),
    xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-15)),
    title_opts=opts.TitleOpts(title="Bar-旋转X轴标签", subtitle="解决标签名字过长的问题"),
)
tree.render("bar_product.html")
